package com.jm.dao.Impl;

import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.jm.dao.UserDao;
import com.jm.pojo.User;
import com.jm.pojo.UserLog;

public class UserDaoImpl  implements UserDao   {

		private HibernateTemplate hibernateTemplate;
		
		@Resource(name="sessionFactory")
		public void setSessionFactory(SessionFactory sessionFactory) {
			this.hibernateTemplate = new HibernateTemplate(sessionFactory);
		}

		@Override
		public boolean deleteDateByName(String name) {
			List<User> lists = selectUsersByName(name);
			for(User u : lists) {
				hibernateTemplate.delete(u);
			}
			return true;
		}

		@Override
		public boolean insertData(Object o) {
			User u = (User) o;
			List list = selectUsersByName(u.getName());
			System.out.println(list.toString());
			if(list.isEmpty() || list.size() == 0) {
				hibernateTemplate.save(u);
				return true;
			}
			
			return false;
		}

		@Override
		public List<Object> selectData() {
			//return hibernateTemplate.find(" from User ");
			return hibernateTemplate.find("select u from User u, UserLog l where u.name=l.userName order by l.insertDate desc");
		}

		@Override
		public int alterDataByName(Object o) {
			User u = (User) o;
			int count = hibernateTemplate.bulkUpdate("update User u set u.password='" + u.getPassword() + "'" + "where u.name='" + u.getName() + "'");
			return count;
		}

		@Override
		public List<User> selectUsersByName(String name) {
			return hibernateTemplate.find(" from User where name = '" + name + "'");
		}

		@Override
		public void saveUserLog(UserLog ul) {
			hibernateTemplate.save(ul);
			
		}
		
}
